package com.xzc.lease.web.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xzc.lease.common.constant.RedisConstant;
import com.xzc.lease.common.exception.LeaseException;
import com.xzc.lease.common.result.ResultCodeEnum;
import com.xzc.lease.common.utils.CodeUtil;
import com.xzc.lease.common.utils.JwtUtil;
import com.xzc.lease.model.entity.UserInfo;
import com.xzc.lease.model.enums.BaseStatus;
import com.xzc.lease.web.app.mapper.UserInfoMapper;
import com.xzc.lease.web.app.service.LoginService;
import com.xzc.lease.web.app.service.SmsService;
import com.xzc.lease.web.app.vo.user.LoginVo;
import com.xzc.lease.web.app.vo.user.UserInfoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private SmsService smsService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 获取短信验证码
     *
     * @param phone
     */
    public void getCode(String phone) {
        //通过编写的工具类获取随机验证码
        String code = CodeUtil.getRandomCode(6);

        //设置该验证码在redis中的 key
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        //hasKey()：判断某个key是否存在
        if (stringRedisTemplate.hasKey(key)) {
            //获取key的 TTL(过期时间)
            Long ttl = stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
            //600s - 当前key的ttl < 60s    说明用户在一分钟内重复发送短信请求
            if (RedisConstant.APP_LOGIN_CODE_TTL_SEC - ttl < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC) {
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }
        //设置验证码的k,v  过期时间为10分钟（测试环境设置为：30天）
        stringRedisTemplate.opsForValue().set(key, code, RedisConstant.APP_LOGIN_CODE_TTL_SEC * 6 * 24 * 30, TimeUnit.SECONDS);

        //发送验证码
        smsService.sendCode(phone, code);
    }

    /**
     * 登录或注册
     *
     * @param loginVo
     */
    public String login(LoginVo loginVo) {
        //判断手机号码、验证码是否为空
        if (loginVo.getPhone() == null)
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        if (loginVo.getCode() == null)
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);

        //通过手机号得到 redis中保存的code
        String code = stringRedisTemplate.opsForValue().get(RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone());
        //判断验证码是否已过期
        if (code == null)
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        //比较前端传来的验证码
        if (!loginVo.getCode().equals(code))
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);

        //根据phone 获取用户信息
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getPhone, loginVo.getPhone());
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
        //用户为空说明是新用户 则注册用户，否则判断用户的状态是否可用
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setNickname("用户-" + loginVo.getPhone().substring(7)); //用户-手机号码后4位
            userInfoMapper.insert(userInfo);
        } else {
            if (userInfo.getStatus().equals(BaseStatus.DISABLE))
                throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }

        return JwtUtil.createToken(userInfo.getId(), userInfo.getPhone());
    }

    /**
     * 获取登录用户信息
     *
     * @param userId
     * @return
     */
    public UserInfoVo getLoginUserById(Long userId) {
        //通过id获取用户信息
        UserInfo userInfo = userInfoMapper.selectById(userId);
        return new UserInfoVo(userInfo.getNickname(), userInfo.getAvatarUrl());
    }
}
